package com.ruoyi.station.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.station.domain.QueryData;
import com.ruoyi.station.domain.SDeviceProperties;
import com.ruoyi.station.domain.SMachineRoom;
import com.ruoyi.station.service.SDevicePropertiesService;
import com.ruoyi.station.util.ParseSql;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

/**
 * 设备属性Controller
 *
 * @author ruoyi
 * @date 2021-08-06
 */
@RestController
@RequestMapping("/properties")
@Api(value="设备属性对象操作资源", tags = "设备属性对象操作资源")
public class SDevicePropertiesController extends BaseController
{
    @Autowired
    private SDevicePropertiesService sDevicePropertiesService;

    @Autowired
    private TokenService tokenService;


    /**
     * 查询设备属性列表
     */
    @PreAuthorize("@ss.hasPermi('system:properties:list')")
    @GetMapping("/list")
    @ApiOperation(value="查询设备属性列表", notes="查询设备属性列表")
    public TableDataInfo list(@ApiParam String equipmentType)
    {
        startPage();
        List<Map> resultList = new ArrayList<>();//结果集
        int i = 1;
        if (StrUtil.isNotEmpty(equipmentType)){
            String equipmentTypeVal = DictUtils.getDictLabel("equipment_type", equipmentType);
            List<SDeviceProperties> sDevicePropertiesList = sDevicePropertiesService.list(new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, equipmentType));
            String collect = sDevicePropertiesList.stream().map(sDeviceProperties -> sDeviceProperties.getDeviceName()).collect(Collectors.joining("、"));
            List<SDeviceProperties> data = sDevicePropertiesService.list(new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, equipmentType));
            Map map = new HashMap();
            map.put("id",i);
            map.put("key",equipmentType);
            map.put("val",equipmentTypeVal);
            map.put("count",collect);
            map.put("data",data);
            resultList.add(map);
            i++;
            return getDataTable(resultList);
        }
        List<SysDictData> dictCache = DictUtils.getDictCache("equipment_type");
        for (SysDictData sysDictData : dictCache) {
            Map map = new HashMap();
            String dictValue = sysDictData.getDictValue();
            int count = sDevicePropertiesService.count(new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, dictValue));
            List<SDeviceProperties> dataList = sDevicePropertiesService.list(
                    new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, dictValue));
            String collect = dataList.stream().map(sDeviceProperties -> sDeviceProperties.getDeviceName()).collect(Collectors.joining("、"));
            if (count > 0){
                map.put("id",i);
                map.put("key",dictValue);
                map.put("val",sysDictData.getDictLabel());
                map.put("count",collect);
                map.put("data",dataList);
                resultList.add(map);
                i++;
            }
        }
        return getDataTable(resultList);
    }

    /**
     * 导出设备属性列表
     */
    @PreAuthorize("@ss.hasPermi('system:properties:export')")
    @Log(title = "设备属性", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value="导出设备属性列表", notes="导出设备属性列表")
    public AjaxResult export(@ApiParam SDeviceProperties sDeviceProperties)
    {
        QueryWrapper<SDeviceProperties> wrapper = new QueryWrapper();
        List<SDeviceProperties> list = sDevicePropertiesService.list(wrapper);
        ExcelUtil<SDeviceProperties> util = new ExcelUtil<SDeviceProperties>(SDeviceProperties.class);
        return util.exportExcel(list, "properties");
    }

    /**
     * 获取设备属性详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:properties:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取设备属性详细信息", notes="获取设备属性详细信息")
    public AjaxResult getInfo(@ApiParam @PathVariable("id") String id)
    {
        return AjaxResult.success(sDevicePropertiesService.getById(id));
    }

    /**
     * 新增或修改设备属性
     */
    @PreAuthorize("@ss.hasPermi('system:properties:add')")
    @Log(title = "设备属性")
    @PostMapping
    @ApiOperation(value="新增设备属性", notes="新增设备属性")
    public AjaxResult add(@ApiParam @RequestBody Map map)
    {
        String ids = (String) map.get("ids");
        JSONArray queryData = JSONUtil.parseArray(map.get("sDevicePropertiesList"));
        List<SDeviceProperties> sDevicePropertiesList = JSONUtil.toList(queryData, SDeviceProperties.class);
        List<String> deviceNameList = sDevicePropertiesList.stream().map(sDeviceProperties -> sDeviceProperties.getDeviceName()).collect(Collectors.toList());
        long count = deviceNameList.stream().distinct().count();
        boolean isRepeat = count < deviceNameList.size();
        if (isRepeat) return AjaxResult.error("属性名称不可重复");
        boolean flag = true;
        for (SDeviceProperties sDeviceProperties : sDevicePropertiesList) {
            if (flag){
                if(sDeviceProperties.getId() != null ){
                    flag = sDevicePropertiesService.update(sDeviceProperties,
                            new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getId, sDeviceProperties.getId()));
                }else {
                    sDeviceProperties.setCreateBy(SecurityUtils.getUsername());
                    flag = sDevicePropertiesService.save(sDeviceProperties);
                }
            }else {
                return AjaxResult.error("操作失败！");
            }
        }
        String[] split = ids.split(",");
        for (String s : split) {
            sDevicePropertiesService.removeById(s);
        }
        return AjaxResult.success("操作成功！");
    }

    /**
     * 修改设备属性
     */
    @PreAuthorize("@ss.hasPermi('system:properties:edit')")
    @Log(title = "设备属性", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改设备属性", notes="修改设备属性")
    public AjaxResult edit(@ApiParam @RequestBody SDeviceProperties sDeviceProperties)
    {
        int result = sDevicePropertiesService.updateById(sDeviceProperties) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 删除设备属性
     */
    @PreAuthorize("@ss.hasPermi('system:properties:remove')")
    @Log(title = "设备属性")
    @DeleteMapping("/remove")
    @ApiOperation(value="删除设备属性", notes="删除设备属性")
    public AjaxResult remove(@ApiParam String equipmentType)
    {
        List<SDeviceProperties> data = sDevicePropertiesService.list(new LambdaQueryWrapper<SDeviceProperties>().eq(SDeviceProperties::getEquipmentType, equipmentType));
        boolean flag = true;
        for (SDeviceProperties datum : data) {
            if (flag){
                flag = sDevicePropertiesService.removeById(datum.getId());
            }else {
                return AjaxResult.error("删除失败！");
            }
        }
        return AjaxResult.success("删除成功！");
    }

    /**
     * 导出设备属性模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SDeviceProperties> util = new ExcelUtil<>(SDeviceProperties.class);
        return util.importTemplateExcel("设备属性数据");
    }

    @Log(title = "导入设备属性管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:properties:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SDeviceProperties> util = new ExcelUtil<>(SDeviceProperties.class);
        List<SDeviceProperties> sDeviceProperties = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String message = sDevicePropertiesService.importDeviceProperties(sDeviceProperties, updateSupport, loginUser.getUsername());
        return AjaxResult.success(message);
    }
}
